#!/usr/bin/env python
# encoding: utf-8
"""
FCA.py

Created by Pablo Ortega Mesa on 2011-03-30.
Copyright (c) 2011 Toeska. All rights reserved.
"""

import sys
import os
import getopt
import re


class FCA():
	''' loaded data like: list of docs, terms, and frecuencies '''
	def __init__(self,termsFilename,pathDocs):
		self.terms = self.__readTerms__(termsFilename)
		self.docs = self.__readDocs__(pathDocs)
		self.freq = self.__readFrecuencies__()
		
	''' read terms and return to save in self var '''
	def __readTerms__(self,filename):
		terms = []
		termsFile = open(filename,'r')
		for line in termsFile:
			line = line.split("\n")[0]
			terms.append(line)
		termsFile.close()
		print "Load "+str(len(terms))+" terms"
		return terms
	
	''' read list of docs and return to save in self var '''
	def __readDocs__(self,path):
		filesPossible = os.listdir(path)
		files = []
		for f in filesPossible:
			if re.search('(txt)$',f):
				files.append(path+f)
		print "Listed "+str(len(files))+" docs"
		return files
		
	def __readFrecuencies__(self):
		frequencies = []
		for term in self.terms:
			freqTerm = []
			for f in self.docs:
				dataFile = open(f,'r')
				data = dataFile.read()
				dataFile.close()
				patron = re.compile('.*('+term+').*',re.IGNORECASE)
				if patron.search(data):
					founds = patron.findall(data)
					cont = len(founds)
				else:
					cont = 0
				freqTerm.append(cont)
			frequencies.append(freqTerm)
		print "Calculate matrix("+str(len(frequencies))+","+str(len(frequencies[0]))+") of frecuencies"
		return frequencies
		
	
	
	def writeContext(self,filename,TFIDF, threshold=0,name="Default Name",nameDataset="Name_of_dataset"):
		contextFile = open(filename,'w')
		contextFile.write("[Relational Context]\n")
		contextFile.write(name+"\n")
		contextFile.write("[Binary Relation]\n")
		contextFile.write(nameDataset+"\n")
		
		
		'''prepare docs names '''
		docsName = []
		for doc in self.docs:
			name = doc.split("/")[-1]
			docsName.append(name)
		docString = ''
		for doc in docsName:
			docString += doc + ' | '
		contextFile.write(docString+"\n")
		termString = ''
		for term in self.terms:
			termString += term + ' | '
		contextFile.write(termString+"\n")
		for i in xrange(0,len(TFIDF)):
			for j in xrange(0,len(TFIDF[i])):
				if TFIDF[i][j] > threshold:
					contextFile.write("1 ")
				else:
					contextFile.write("0 ")
			contextFile.write("\n")
		contextFile.write("[END Relational Context]")
		contextFile.close()
		print "End context generated"
	
	def getTerms(self):
		return self.terms
	
	def getDocs(self):
		return self.docs
		
	def getFreq(self):
		return self.freq